#coding=utf-8
'''
Created on 2017-06-12

@author: sandy
'''

import sys,platform,os
import logging
sys.path.append("../")
from twisted.internet import reactor
from pycommon import daemon
from pycommon import logmanager
from pycommon import daemonconfig
import website
import serverconfig
import clientfactory
import accountconfig

if 'twisted.internet.reactor' not in sys.modules: 
    if platform.system() == "Linux":
        from twisted.internet import epollreactor
        epollreactor.install()  
    else:
        from twisted.internet import iocpreactor
        iocpreactor.install()

def serverStart(isdaemon):
    logging.info("############ %s[%d] start ############",serverconfig.instance.server_name,os.getpid())
    clientfactory.instance.start(serverconfig.instance.server_ip,serverconfig.instance.server_port,serverconfig.instance.max_client)
    website.instance.start(serverconfig.instance.web_ip,serverconfig.instance.web_port)
    pass

def serverStop():
    website.instance.stop()
    clientfactory.instance.stop()
    pass  

def daemonFunc(isdaemon):
    logmanager.instance.setupLog(daemonconfig.instance.loglevel,daemonconfig.instance.logfile,isdaemon)
    serverconfig.instance.loadFromFile()
    accountconfig.instance.loadFromFile()
    serverStart(isdaemon)
    reactor.run()
    serverStop()

def run():
    daemonconfig.instance.parse(serverconfig.instance.rundir)
    daemon.run(daemonconfig.instance.pidpath, daemonFunc)

if __name__ == "__main__":
    run()